package com.iwomy.secureplat.common.websocket.holder;

import cn.hutool.core.util.ObjectUtil;
import org.springframework.web.socket.WebSocketSession;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * WebSocketSession 持有者 主要用于保存当前所有在线的会话信息
 *
 * @author Hccake 2021/1/4
 * @version 1.0
 */
public final class WebSocketSessionHolder {

	private WebSocketSessionHolder() {
	}

	private static final Map<String, Map<String, WebSocketSession>> USER_SESSION_MAP = new ConcurrentHashMap<>();

	/**
	 * 添加一个 session
	 *
	 * @param sessionKey session 唯一标识
	 * @param session    待添加的 WebSocketSession
	 */
	public static void addSession(Object sessionKey, WebSocketSession session) {
		Map<String, WebSocketSession> webSocketSessions = USER_SESSION_MAP.get(sessionKey.toString());
		if (ObjectUtil.isEmpty(webSocketSessions)) {
			webSocketSessions = new ConcurrentHashMap<>();
			USER_SESSION_MAP.put(sessionKey.toString(), webSocketSessions);
		}
		webSocketSessions.put(session.getId(), session);
	}

	/**
	 * 删除一个 session
	 *
	 * @param sessionKey session唯一标识
	 */
	public static void removeSession(Object sessionKey,WebSocketSession session) {
		Map<String, WebSocketSession> map = USER_SESSION_MAP.get(sessionKey.toString());
		map.remove(session.getId());
	}

	/**
	 * 获取指定标识的 session
	 *
	 * @param sessionKey session唯一标识
	 * @return WebSocketSession 该标识对应的 session
	 */
	public static List<WebSocketSession> getSession(Object sessionKey) {
		Map<String, WebSocketSession> stringWebSocketSessionMap = USER_SESSION_MAP.get(sessionKey.toString());
		if(ObjectUtil.isNull(stringWebSocketSessionMap)) return Collections.emptyList();
		List<WebSocketSession> list = stringWebSocketSessionMap.entrySet().stream().map(val -> {
			return val.getValue();
		}).collect(Collectors.toList());
		return list;
	}

	/**
	 * 获取当前所有在线的 session
	 *
	 * @return Collection<WebSocketSession> session集合
	 */
	public static Collection<WebSocketSession> getSessions() {
		List<WebSocketSession> list = new ArrayList<>();
		USER_SESSION_MAP.entrySet().stream().forEach(val -> {
			Map<String, WebSocketSession> map = val.getValue();
			map.entrySet().stream().forEach(x -> {
				list.add(x.getValue());
			});
		});
		return list;
	}

	/**
	 * 获取所有在线的用户标识
	 *
	 * @return Set<Object> session唯一标识集合
	 */
	public static Set<String> getSessionKeys() {
		return USER_SESSION_MAP.keySet();
	}

}
